﻿namespace Antivirus.Domain.Extensions
{
    using System.Collections.Generic;

    public static class StringExtensions
    {
        private const string HexCharacters = "0123456789ABCDEF";

        public static byte[] AsHexString(this string value)
        {
            if (value.Length % 2 == 1)
                return null;

            value = value.ToUpperInvariant();
            var result = new List<byte>();

            for (var i = 0; i < value.Length / 2; i++)
            {
                var hexValue = GetByteValue(value[i*2], value[i*2 + 1]);
                result.Add(hexValue);
            }

            return result.ToArray();
        }

        private static byte GetByteValue(char firstDigit, char secondDigit)
        {
            return (byte) (HexCharacters.IndexOf(firstDigit)*16 + HexCharacters.IndexOf(secondDigit));
        }
    }
}